import { fetchDataGet, fetchDataPost } from "@/api";
import { ref } from "vue";

//  处理 get 请求
export function useFetchGet(url: string, formatData: Function = data => data, isToken: boolean = true): any[] {
  const _data: any = ref({});

  async function setData(data: any) {
    try {
      const res: any = await fetchDataGet(url, data, isToken);
      return _data.value = formatData(res || {});
    } catch (error) {
      return {};
    }

  }

  return [_data, setData];
}

//  post 请求
export function useFetchPost(url: string, formatData?: any, isToken: boolean = true): any[] {
  const _data: any = ref({});

  async function setData(data: any) {
    //  清空原数组
    _data.value = {};

    const res: any = await fetchDataPost(url, data, isToken);

    return _data.value = formatData ? formatData(res || {}) : res;
  }

  return [_data, setData];
}